import { ref, Ref } from 'vue';
import type { Cell, Column } from '../types';

// 定义更具体的函数类型
type SaveStateFn = () => void;

export function useTableOperations(tableData: Ref<Cell[][]>, columns: Ref<Column[]>, selectedCells: Ref<Set<string>>, saveState: SaveStateFn) {
  // 表格操作
  const addRow = (position?: number) => {
    const newRow: Cell[] = [];
    for (let j = 0; j < columns.value.length; j++) {
      newRow.push({
        name: '',
        id: '',
        type: '',
        brandId: '',
        customerId: ''
      });
    }
    if (position !== undefined && position >= 0 && position <= tableData.value.length) {
      tableData.value.splice(position, 0, newRow);
    } else {
      tableData.value.push(newRow);
    }
    saveState();
  };

  const addColumn = (position?: number) => {
    const getColumnLetter = (index: number): string => {
      let letter = '';
      while (index >= 0) {
        letter = String.fromCharCode(65 + (index % 26)) + letter;
        index = Math.floor(index / 26) - 1;
      }
      return letter;
    };

    const columnIndex = position !== undefined && position >= 0 && columns.value ? position : columns.value.length;

    columns.value.splice(columnIndex, 0, { name: getColumnLetter(columnIndex) });

    for (const row of tableData.value) {
      row.splice(columnIndex, 0, {
        name: '',
        id: '',
        type: '',
        brandId: '',
        customerId: ''
      });
    }
    saveState();
  };

  const deleteSelected = () => {
    selectedCells.value.forEach((cellId) => {
      const [row, col] = cellId.split('-').map(Number);
      if (tableData.value[row] && tableData.value[row][col]) {
        tableData.value[row][col] = {
          name: '',
          id: '',
          type: '',
          brandId: '',
          customerId: ''
        };
      }
    });
    saveState();
  };

  return {
    addRow,
    addColumn,
    deleteSelected
  };
}
